﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "添加工艺流程";
}
<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />

<script src="~/layui/layui.js"></script>
<script src="~/js/site.js"></script>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>

<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">添加工艺流程</h3>
                    <div class="card-tools">
                        <a href="/Home/GetProductProcess" class="btn btn-secondary btn-sm">
                            <i class="layui-icon layui-icon-return"></i> 返回列表
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <form id="addProcessForm">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="processName" class="form-label">工艺名称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="processName" name="processName" 
                                           placeholder="请输入工艺名称" required>
                                    <div class="invalid-feedback">
                                        请输入工艺名称
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="processCode" class="form-label">工艺编码 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="processCode" name="processCode" 
                                           placeholder="请输入工艺编码" required>
                                    <div class="invalid-feedback">
                                        请输入工艺编码
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="order" class="form-label">排序 <span class="text-danger">*</span></label>
                                    <input type="number" class="form-control" id="order" name="order" 
                                           placeholder="请输入排序号" required min="1">
                                    <div class="invalid-feedback">
                                        请输入有效的排序号
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="leaderId" class="form-label">负责人 <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="leaderName" name="leaderName" 
                                               placeholder="请选择负责人" readonly required>
                                        <input type="hidden" id="leaderId" name="leaderId" required>
                                        <div class="input-group-append">
                                            <button type="button" class="btn btn-outline-secondary" id="btnSelectLeader">
                                                <i class="layui-icon layui-icon-search"></i> 选择
                                            </button>
                                        </div>
                                    </div>
                                    <div class="invalid-feedback">
                                        请选择负责人
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="workOrderId" class="form-label">生产工单 <span class="text-danger">*</span></label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" id="workOrderName" name="workOrderName" 
                                               placeholder="请选择生产工单" readonly required>
                                        <input type="hidden" id="workOrderId" name="workOrderId" required>
                                        <div class="input-group-append">
                                            <button type="button" class="btn btn-outline-secondary" id="btnSelectWorkOrder">
                                                <i class="layui-icon layui-icon-search"></i> 选择
                                            </button>
                                        </div>
                                    </div>
                                    <div class="invalid-feedback">
                                        请选择生产工单
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="flow" class="form-label">工艺流程 <span class="text-danger">*</span></label>
                                    <textarea class="form-control" id="flow" name="flow" 
                                              rows="3" placeholder="请输入工艺流程描述" required></textarea>
                                    <div class="invalid-feedback">
                                        请输入工艺流程描述
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row mt-4">
                            <div class="col-12">
                                <div class="form-group text-center">
                                    <button type="submit" class="btn btn-primary" id="btnSubmit">
                                        <i class="layui-icon layui-icon-ok"></i> 提交
                                    </button>
                                    <button type="button" class="btn btn-secondary ml-2" id="btnReset">
                                        <i class="layui-icon layui-icon-refresh"></i> 重置
                                    </button>
                                    <a href="/Home/GetProductProcess" class="btn btn-outline-secondary ml-2">
                                        <i class="layui-icon layui-icon-close"></i> 取消
                                    </a>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 负责人选择对话框 -->
<div class="modal fade" id="leaderModal" tabindex="-1" role="dialog" aria-labelledby="leaderModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="leaderModalLabel">选择负责人</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <div class="input-group">
                            <input type="text" class="form-control" id="leaderSearchInput" placeholder="搜索负责人姓名或部门...">
                            <div class="input-group-append">
                                <button class="btn btn-outline-secondary" type="button" id="btnSearchLeader">
                                    <i class="layui-icon layui-icon-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="leaderTable">
                        <thead class="thead-light">
                            <tr>
                                <th width="80">序号</th>
                                <th>负责人ID</th>
                                <th>负责人姓名</th>
                                <th>所属部门</th>
                                <th width="100">操作</th>
                            </tr>
                        </thead>
                        <tbody id="leaderTableBody">
                            <!-- 数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
                <div id="leaderLoading" class="text-center" style="display: none;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 加载中...
                </div>
                <div id="leaderNoData" class="text-center text-muted" style="display: none;">
                    暂无负责人数据
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>

<!-- 生产工单选择对话框 -->
<div class="modal fade" id="workOrderModal" tabindex="-1" role="dialog" aria-labelledby="workOrderModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="workOrderModalLabel">选择生产工单</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <div class="input-group">
                            <input type="text" class="form-control" id="workOrderSearchInput" placeholder="搜索工单编号、名称或状态...">
                            <div class="input-group-append">
                                <button class="btn btn-outline-secondary" type="button" id="btnSearchWorkOrder">
                                    <i class="layui-icon layui-icon-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered table-hover" id="workOrderTable">
                        <thead class="thead-light">
                            <tr>
                                <th width="60">序号</th>
                                <th>工单ID</th>
                                <th>工单编号</th>
                                <th>工单名称</th>
                                <th>工单状态</th>
                                <th>负责人</th>
                                <th>订单数量</th>
                                <th>产品</th>
                                <th>工单日期</th>
                                <th width="100">操作</th>
                            </tr>
                        </thead>
                        <tbody id="workOrderTableBody">
                            <!-- 数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
                <div id="workOrderLoading" class="text-center" style="display: none;">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 加载中...
                </div>
                <div id="workOrderNoData" class="text-center text-muted" style="display: none;">
                    暂无工单数据
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function () {
        // 表单提交事件
        $('#addProcessForm').on('submit', function (e) {
            e.preventDefault();
            submitForm();
        });

        // 重置按钮事件
        $('#btnReset').click(function () {
            resetForm();
        });

        // 负责人选择按钮事件
        $('#btnSelectLeader').click(function () {
            openLeaderModal();
        });

        // 负责人搜索按钮事件
        $('#btnSearchLeader').click(function () {
            searchLeaders();
        });

        // 负责人搜索框回车事件
        $('#leaderSearchInput').keypress(function (e) {
            if (e.which === 13) {
                searchLeaders();
            }
        });

        // 工单选择按钮事件
        $('#btnSelectWorkOrder').click(function () {
            openWorkOrderModal();
        });

        // 工单搜索按钮事件
        $('#btnSearchWorkOrder').click(function () {
            searchWorkOrders();
        });

        // 工单搜索框回车事件
        $('#workOrderSearchInput').keypress(function (e) {
            if (e.which === 13) {
                searchWorkOrders();
            }
        });

        // 提交表单
        function submitForm() {
            // 验证表单
            if (!validateForm()) {
                return;
            }

            // 显示加载状态
            showLoading();

            // 收集表单数据
            const formData = {
                processName: $('#processName').val().trim(),
                processCode: $('#processCode').val().trim(),
                order: parseInt($('#order').val()),
                flow: $('#flow').val().trim(),
                leaderId: parseInt($('#leaderId').val()),
                workOrderId: parseInt($('#workOrderId').val())
            };

            // 调用后端API
            $.ajax({
                url: 'http://localhost:5025/api/Production/AddProcess',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function (response) {
                    hideLoading();
                    if (response.code === 200) {
                        showSuccess('添加工艺流程成功！');
                       
                    } else {
                        showError('添加失败：' + response.msg);
                    }
                },
                error: function (xhr, status, error) {
                    hideLoading();
                    let errorMsg = '请求失败';
                    if (xhr.responseJSON && xhr.responseJSON.msg) {
                        errorMsg += '：' + xhr.responseJSON.msg;
                    } else {
                        errorMsg += '：' + error;
                    }
                    showError(errorMsg);
                }
            });
        }

        // 验证表单
        function validateForm() {
            let isValid = true;
            const requiredFields = [
                'processName',
                'processCode', 
                'order',
                'flow',
                'leaderId',
                'workOrderId'
            ];

            // 清除之前的验证状态
            $('.form-control').removeClass('is-invalid');

            // 验证必填字段
            requiredFields.forEach(function (fieldName) {
                const field = $('#' + fieldName);
                const value = field.val().trim();
                
                if (!value) {
                    field.addClass('is-invalid');
                    isValid = false;
                } else {
                    field.addClass('is-valid');
                }
            });

            // 验证数字字段
            const order = parseInt($('#order').val());
            if (isNaN(order) || order <= 0) {
                $('#order').addClass('is-invalid');
                isValid = false;
            }

            // 验证负责人选择
            const leaderId = $('#leaderId').val();
            if (!leaderId) {
                $('#leaderName').addClass('is-invalid');
                isValid = false;
            }

            // 验证工单选择
            const workOrderId = $('#workOrderId').val();
            if (!workOrderId) {
                $('#workOrderName').addClass('is-invalid');
                isValid = false;
            }

            return isValid;
        }

        // 重置表单
        function resetForm() {
            $('#addProcessForm')[0].reset();
            $('.form-control').removeClass('is-invalid is-valid');
            
            // 清空负责人选择
            $('#leaderId').val('');
            $('#leaderName').val('');
            
            // 清空工单选择
            $('#workOrderId').val('');
            $('#workOrderName').val('');
        }

        // 显示加载状态
        function showLoading() {
            $('#btnSubmit').prop('disabled', true).html('<i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 提交中...');
        }

        // 隐藏加载状态
        function hideLoading() {
            $('#btnSubmit').prop('disabled', false).html('<i class="layui-icon layui-icon-ok"></i> 提交');
        }

        // 显示成功消息
        function showSuccess(message) {
            layer.msg(message, {
                icon: 1,
                time: 2000
            });
        }

        // 显示错误消息
        function showError(message) {
            layer.msg(message, {
                icon: 2,
                time: 3000
            });
        }

        // 实时验证
        $('.form-control').on('blur', function () {
            const field = $(this);
            const value = field.val().trim();
            
            if (field.attr('required') && !value) {
                field.addClass('is-invalid');
            } else {
                field.removeClass('is-invalid').addClass('is-valid');
            }
        });

        // 负责人相关函数
        let leaderData = [];

        // 打开负责人选择对话框
        function openLeaderModal() {
            $('#leaderModal').modal('show');
            loadLeaderData();
        }

        // 加载负责人数据
        function loadLeaderData() {
            showLeaderLoading();
            
            $.ajax({
                url: 'http://localhost:5025/api/Production/GetLeader',
                type: 'GET',
                success: function (response) {
                    hideLeaderLoading();
                    if (response.code === 200) {
                        leaderData = response.data || [];
                        renderLeaderTable(leaderData);
                    } else {
                        showLeaderError('加载负责人数据失败：' + response.msg);
                    }
                },
                error: function (xhr, status, error) {
                    hideLeaderLoading();
                    showLeaderError('请求失败：' + error);
                }
            });
        }

        // 搜索负责人
        function searchLeaders() {
            const keyword = $('#leaderSearchInput').val().trim().toLowerCase();
            
            if (!keyword) {
                renderLeaderTable(leaderData);
                return;
            }

            const filteredData = leaderData.filter(function (leader) {
                return leader.leaderName.toLowerCase().includes(keyword) ||
                       leader.departmentName.toLowerCase().includes(keyword) ||
                       leader.leaderId.toString().includes(keyword);
            });

            renderLeaderTable(filteredData);
        }

        // 渲染负责人表格
        function renderLeaderTable(data) {
            const tbody = $('#leaderTableBody');
            tbody.empty();

            if (data.length === 0) {
                $('#leaderNoData').show();
                return;
            }

            $('#leaderNoData').hide();
            data.forEach((leader, index) => {
                const row = `
                    <tr>
                        <td>${index + 1}</td>
                        <td>${leader.leaderId}</td>
                        <td>${leader.leaderName}</td>
                        <td>${leader.departmentName}</td>
                        <td>
                            <button type="button" class="btn btn-sm btn-primary" onclick="selectLeader(${leader.leaderId}, '${leader.leaderName}', '${leader.departmentName}')">
                                选择
                            </button>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
        }

        // 选择负责人
        window.selectLeader = function (leaderId, leaderName, departmentName) {
            $('#leaderId').val(leaderId);
            $('#leaderName').val(leaderName + ' (' + departmentName + ')');
            
            // 清除验证状态
            $('#leaderName').removeClass('is-invalid').addClass('is-valid');
            
            // 关闭对话框
            $('#leaderModal').modal('hide');
            
            // 显示成功提示
            layer.msg('已选择负责人：' + leaderName, {
                icon: 1,
                time: 1500
            });
        };

        // 显示负责人加载状态
        function showLeaderLoading() {
            $('#leaderLoading').show();
            $('#leaderTable').hide();
            $('#leaderNoData').hide();
        }

        // 隐藏负责人加载状态
        function hideLeaderLoading() {
            $('#leaderLoading').hide();
            $('#leaderTable').show();
        }

        // 显示负责人错误信息
        function showLeaderError(message) {
            $('#leaderTableBody').html(`<tr><td colspan="5" class="text-center text-danger">${message}</td></tr>`);
            $('#leaderTable').show();
        }

        // 工单相关函数
        let workOrderData = [];

        // 打开工单选择对话框
        function openWorkOrderModal() {
            $('#workOrderModal').modal('show');
            loadWorkOrderData();
        }

        // 加载工单数据
        function loadWorkOrderData() {
            showWorkOrderLoading();
            
            $.ajax({
                url: 'http://localhost:5025/api/Production/GetWorkOrder',
                type: 'GET',
                success: function (response) {
                    hideWorkOrderLoading();
                    if (response.code === 200) {
                        workOrderData = response.data || [];
                        renderWorkOrderTable(workOrderData);
                    } else {
                        showWorkOrderError('加载工单数据失败：' + response.msg);
                    }
                },
                error: function (xhr, status, error) {
                    hideWorkOrderLoading();
                    showWorkOrderError('请求失败：' + error);
                }
            });
        }

        // 搜索工单
        function searchWorkOrders() {
            const keyword = $('#workOrderSearchInput').val().trim().toLowerCase();
            
            if (!keyword) {
                renderWorkOrderTable(workOrderData);
                return;
            }

            const filteredData = workOrderData.filter(function (workOrder) {
                return workOrder.workOrderCode.toLowerCase().includes(keyword) ||
                       workOrder.workOrderName.toLowerCase().includes(keyword) ||
                       workOrder.workOrderId.toString().includes(keyword) ||
                       getWorkOrderStateText(workOrder.workOrderState).toLowerCase().includes(keyword);
            });

            renderWorkOrderTable(filteredData);
        }

        // 渲染工单表格
        function renderWorkOrderTable(data) {
            const tbody = $('#workOrderTableBody');
            tbody.empty();

            if (data.length === 0) {
                $('#workOrderNoData').show();
                $('#workOrderTable').hide();
                return;
            }

            $('#workOrderNoData').hide();
            $('#workOrderTable').show();
            
            data.forEach((workOrder, index) => {
                const row = `
                    <tr>
                        <td>${index + 1}</td>
                        <td>${workOrder.workOrderId}</td>
                        <td>${workOrder.workOrderCode || '-'}</td>
                        <td>${workOrder.workOrderName || '-'}</td>
                        <td>${getWorkOrderStateText(workOrder.workOrderState)}</td>
                        <td>${workOrder.leaderName || '-'}</td>
                        <td>${workOrder.orderNum || 0}</td>
                        <td>${workOrder.productName || '-'}</td>
                        <td>${formatDateTime(workOrder.workOrderDate)}</td>
                        <td>
                            <button type="button" class="btn btn-sm btn-primary" onclick="selectWorkOrder(${workOrder.workOrderId}, '${workOrder.workOrderCode}', '${workOrder.workOrderName}')">
                                选择
                            </button>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
        }

        // 选择工单
        window.selectWorkOrder = function (workOrderId, workOrderCode, workOrderName) {
            $('#workOrderId').val(workOrderId);
            $('#workOrderName').val(workOrderCode + ' - ' + workOrderName);
            
            // 清除验证状态
            $('#workOrderName').removeClass('is-invalid').addClass('is-valid');
            
            // 关闭对话框
            $('#workOrderModal').modal('hide');
            
            // 显示成功提示
            layer.msg('已选择工单：' + workOrderCode, {
                icon: 1,
                time: 1500
            });
        };

        // 获取工单状态文本
        function getWorkOrderStateText(state) {
            const stateMap = {
                1: '已下达',
                2: '已上线',
                3: '已完成',
                4: '已取消'
            };
            return stateMap[state] || '未知';
        }

        // 格式化日期时间
        function formatDateTime(dateTimeString) {
            if (!dateTimeString) return '-';
            const date = new Date(dateTimeString);
            return date.toLocaleString('zh-CN', { 
                year: 'numeric', 
                month: '2-digit', 
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }

        // 显示工单加载状态
        function showWorkOrderLoading() {
            $('#workOrderLoading').show();
            $('#workOrderTable').hide();
            $('#workOrderNoData').hide();
        }

        // 隐藏工单加载状态
        function hideWorkOrderLoading() {
            $('#workOrderLoading').hide();
            $('#workOrderTable').show();
        }

        // 显示工单错误信息
        function showWorkOrderError(message) {
            $('#workOrderTableBody').html(`<tr><td colspan="10" class="text-center text-danger">${message}</td></tr>`);
            $('#workOrderTable').show();
            $('#workOrderNoData').hide();
        }
    });
</script>

<style>
    .card {
        margin: 20px;
        box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    }
    
    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #f8f9fa;
        border-bottom: 1px solid #dee2e6;
    }
    
    .form-label {
        font-weight: 500;
        margin-bottom: 0.5rem;
    }
    
    .form-control:focus {
        border-color: #80bdff;
        box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
    }
    
    .is-valid {
        border-color: #28a745;
    }
    
    .is-invalid {
        border-color: #dc3545;
    }
    
    .btn {
        padding: 0.375rem 0.75rem;
        font-size: 1rem;
        line-height: 1.5;
        border-radius: 0.25rem;
    }
    
    .btn:disabled {
        opacity: 0.65;
        cursor: not-allowed;
    }
    
    .layui-icon {
        font-size: 14px;
        margin-right: 4px;
    }
    
    .text-danger {
        color: #dc3545 !important;
    }
    
    .form-group {
        margin-bottom: 1rem;
    }
    
    .card-tools {
        display: flex;
        align-items: center;
    }
    
    /* 负责人选择对话框样式 */
    .modal-lg {
        max-width: 900px;
    }
    
    .modal-xl {
        max-width: 1200px;
    }
    
    .modal-body {
        max-height: 500px;
        overflow-y: auto;
    }
    
    .table th {
        background-color: #f8f9fa;
        border-color: #dee2e6;
        font-weight: 500;
    }
    
    .btn-sm {
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
    }
    
    #leaderSearchInput, #workOrderSearchInput {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
    }
    
    #btnSearchLeader, #btnSearchWorkOrder {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
    }
    
    .input-group-append .btn {
        border-left: 0;
    }
</style>
